package com.zlcx.tz.live.repository;

import com.zlcx.tz.live.domain.LiveRoomPublisherRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/4/18 10:11
 * @copyright: Copyright (c) founders
 */
@Repository
public interface LiveRoomPublisherRecordRepository extends JpaRepository<LiveRoomPublisherRecord, Long>, JpaSpecificationExecutor<LiveRoomPublisherRecord> {

    @Query(value = "SELECT p.* FROM live_room_publisher_record p " +
            "LEFT JOIN live_room_info r ON r.id=p.room_id " +
            "left join live_room_join_record lrjr on p.room_id = lrjr.room_id and p.user_id = lrjr.user_id " +
            "WHERE p.publisher_state in('2') AND (r.room_state IN('3','4') or lrjr.id is null)",nativeQuery = true)
    List<LiveRoomPublisherRecord> getNotNonalQuitPublisher();

    @Query(value = "SELECT p.* FROM live_room_publisher_record p \n" +
            "WHERE p.publisher_state='1' AND p.apply_time <=:now",nativeQuery = true)
    List<LiveRoomPublisherRecord> getNoCancelTimeoutRecord(@Param("now")Date now);

    LiveRoomPublisherRecord findFirstByUserIdOrderByCreateTimeDesc(Long userId);

    LiveRoomPublisherRecord findFirstByRoomIdAndUserIdAndPublisherStateInOrderByCreateTimeDesc(@Param("roomId")Long roomId,
                                                                                               @Param("userId")Long userId,@Param("publisherState")List<Integer> status);

    List<LiveRoomPublisherRecord> findByRoomId(Long id);

    LiveRoomPublisherRecord findFirstByUserIdAndPublisherState(Long userId, Integer publisherState);

    @Transactional(rollbackOn=Exception.class)
    @Modifying(clearAutomatically = true)
    @Query("UPDATE LiveRoomPublisherRecord lpr SET lpr.publisherState = 4 , lpr.quitTime =:updateTime , lpr.updateTime=:updateTime WHERE lpr.roomId =:roomId AND lpr.publisherState in(1,2) ")
    int quitAll(  @Param("roomId")Long roomId,@Param("updateTime")Date updateTime);

    List<LiveRoomPublisherRecord> findAllByUserIdInAndPublisherState(List<Long> userIds, Integer publisherState);
}
